package com.hmdp.common.lock.impl;

import com.hmdp.common.lock.ILock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @Auther: 公众号/B站：是叶十三
 * @Date: 2022/11/18
 * @Description: com.hmdp.common.lock.impl
 * @version: 1.0
 */
public class SimpleRedisLock implements ILock {

    private RedisTemplate redisTemplate;

    public static final String KEY_PREFIX = "lock:";

    private String name;

    public SimpleRedisLock(String name,RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.name = name;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        //  获取当前线程标识
        long threadId = Thread.currentThread().getId();
        Boolean success = redisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId + "", timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unlock() {
        redisTemplate.delete(KEY_PREFIX + name);
    }
}
